#include "global.h"

// Command function pointer
typedef (*command)(char*);

// Available commands
void cmdfork(char* options);
void cmdswitch(char* options);
void cmdwait(char* options);
void cmdstatus(char* options);
void cmdhelp(char* options);
void cmdquit(char* options);
void cmdumode(char* options);
void changeColor();

// Variables used to do commands
char	commandNames[8][7] = { "fork", "switch", "wait", "status",
			"help", "quit", "umode", "color" };			
command	commands[8] = { cmdfork, cmdswitch, cmdwait, cmdstatus,
			cmdhelp, cmdquit, cmdumode, changeColor };

// This is the code each process runs when in kernel mode
void processBody()
{
	int i;
	char cmd[20];
	while(1)
	{
		printf("\n-----------------------------------------------------\n");
		printf("This is processs %d at segment 0x%x     Parent ID is %d\n",
			running->processID, running->userStackSegment,
			running->parentProcessID);
		printf("Free queue:  "); printQueue(&freeQueue);
		printf("Ready queue: "); printQueue(&readyQueue);
		printf("Sleep queue: "); printQueue(&sleepQueue);
		printf("-----------------------------------------------------\n");
		printf("Input command: ", running->processID);
		
		gets(cmd);
		
		printf("\n\n");
		for (i = 0; i < 9; ++i)
		{
			if (strcmp(commandNames[i], cmd) == 0)
			{
				(*commands[i])("");
				break;
			}
		}
	}
}

void cmdfork(char* options)
{
	int childPid = kfork();
	if (childPid > -1)
		printf("  * P%d forked child P%d at segment 0x%x\n", running->processID, childPid, 0x1000 * (childPid + 1));
}

void cmdswitch(char* options)
{
	printf("  * P%d giving up CPU\n", running->processID);
	tswitch();
}

void cmdwait(char* options)
{
	int status;
	if (kwait(&status) > -1)
		printf("  * Exit code: %d\n", status);
}

void cmdstatus(char* options)
{
	printf("status\n");
}

void cmdhelp(char* options)
{
	printf("Commands -> | fork | switch | wait | status | help | quit |\n");
}

void cmdquit(char* options)
{
	char exitVal = 0;
	do
	{
		printf("  * Gimme exit value (0-9): ");
		exitVal = getc();
		printf("%c\n", exitVal);
	} while ((exitVal < '0') && (exitVal > '9'));
	kexit(exitVal - '0');
}

void cmdumode(char* options)
{
	goUmode();
}
